
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, InputComponent, Paging } from '../../../componet/index';
import { Switch, Modal, message, } from 'antd';
import './SpecialEducation.scss';
import '../Style/table.scss';
import axios from '../../../axios';
import { PlusOutlined, FormOutlined, DeleteOutlined } from '@ant-design/icons';

export default function PoliciesAndRegulations() {
    const navigate = useNavigate();
    const [data, setData] = useState([]);
    const [type, setType] = useState([]);
    const [SearchType, setSearchType] = useState('');
    const [SearchTitle, setSearchTitle] = useState('');
    const [resetButtonDisabled, setResetButtonDisabled] = useState(true); // 添加一个状态来跟踪重置按钮是否应该被禁用
    //模态框
    // 编辑
    const [TypeEditState, setTypeEditState] = useState(false);
    const [TypeEditInit, setTypeEditInit] = useState('');
    const [TypeEditId, setTypeEditId] = useState('');
    function showTypeEditModal(e: any) {
        setTypeEditState(true);
        setTypeEditInit(e.name);
        setTypeEditId(e._id);
    }
    function hideTypeEditModal() {
        setTypeEditState(false);
    }
    function changeTypeEditInit(val: any) {
        setTypeEditInit(val);
    }
    function handleTypeEditOk() {
        axios.post('/specialEducationTypeUpdate', { id: TypeEditId, name: TypeEditInit }).then((res: any) => {
            if (res.code == 200) {
                message.success('修改成功');
                hideTypeEditModal();
                getShowType();
                setTypeEditInit('');
                getShowData();
            }
        })
    }
    //类型新增
    const [updateTypeText, setUpdateTypeText] = useState('');
    const [isTypeUpdate, setIsTypeUpdate] = useState(false);
    const showTypeUpdate = () => {
        setIsTypeUpdate(true);
    };
    const setTypeUpdate = (e: any) => {
        setUpdateTypeText(e);
    }
    const setTypeUpdateServer = () => {
        axios.post('/specialEducationTypeAdd', { name: updateTypeText }).then((res: any) => {
            if (res.code == 200) {
                message.success('添加成功');
                hideTypeUpdate();
                getShowType();
                setUpdateTypeText('')
            }
        })
    }
    const hideTypeUpdate = () => {
        setIsTypeUpdate(false);
    }
    //类型删除
    const [isTypeDelete, setIsTypeDelete] = useState(false);
    const [deleteTypeName, setDeleteType] = useState('');
    const [deleteTypeId, setDeleteTypeId] = useState('')
    const showTypeDelete = () => {
        setIsTypeDelete(true);
    }
    const hideTypeDelete = () => {
        setIsTypeDelete(false);

    }
    const checkTypeDelete = (e: any) => {
        setDeleteType(e.name)
        setDeleteTypeId(e._id)
        showTypeDelete();
    }
    const deleteTypeServer = () => {
        axios.post('/specialEducationTypeDel?id=' + deleteTypeId,).then((res: any) => {
            if (res.code == 200) {
                message.success('删除成功');
                hideTypeDelete()
                getShowType();
                setDeleteTypeId('')
            }
        })
    }

    useEffect(() => {
        // 当 SearchTitle 发生变化时，更新重置按钮的 disabled 状态
        setResetButtonDisabled(SearchTitle === '');
    }, [SearchTitle]);

    // 获取数据
    const getShowData = async () => {
        axios.get(`/specialEducationGet?title=${SearchTitle}&type=${SearchType}&page=${current}&pageSize=${pageSize}`).then((res: any) => {
            setData(res.data);
            setTotal(res.total)
        });
    };

    // 获取数据类型
    const getShowType = () => {
        axios.get('/specialEducationTypeGet').then((res) => {
            setType(res.data);
        });
    };
    //根据类型查询
    const setSearchTypeChange = async (e: any) => {
        console.log(e)
        await setSearchType(e)
        getShowData()
        // setSearchType(e);
    }
    // 搜索状态
    const setSearchTitleChange = (e: any) => {
        setSearchTitle(e);
    };

    // 重置搜索框
    const resetSearch = () => {
        setSearchTitle(''); // 重置搜索标题 specialEducationTop
    };

    const columns = ['标题', '分类', '发布时间', '作者', '查阅次数', '置顶', '首页推荐', '首页轮播', '操作'];

    const [selectedRows, setSelectedRows] = useState<number[]>([]);
    const handleRowSelectionChange = (index: number, checked: boolean) => {
        setSelectedRows(prev => {
            return checked ? [...prev, index] : prev.filter(i => i !== index);
        });
    };
    // 是否置顶
    const onChangeTop = async (...id: any) => {
        // 根据id查找对应数据
        const targetData: any = data.find((item: any) => item._id === id[0]);
        // isTop取反
        let Top = targetData.isTop = !targetData.isTop;
        await axios.post('/specialEducationTop', { id: id[0], top: Top }).then((res: any) => {
            console.log(res);
            if (res.msg == "修改成功") {
                console.log(res, 22);
                getShowData()
            }
        })
    };
    //是否推荐
    const onChangeRecommend = async (...id: any) => {
        // 根据id查找对应数据
        const targetData: any = data.find((item: any) => item._id === id[0]);
        // isTop取反

        let Recommend = targetData.isRecommend = !targetData.isRecommend;

        console.log(Recommend);
        await axios.post('/specialEducationRecommend', { id: id[0], Recommend: Recommend }).then((res: any) => {
            if (res.res == "修改成功") {
                getShowData()
            }
        })
    };
    //是否轮播
    const onChangeCarousel = async (...id: any) => {
        // 根据id查找对应数据
        const targetData: any = data.find((item: any) => item._id === id[0]);
        // isTop取反

        let Carousel = targetData.isCarousel = !targetData.isCarousel;

        console.log(Carousel);
        await axios.post('/specialEducationCarousel', { id: id[0], Carousel: Carousel }).then((res: any) => {
            if (res.res == "修改成功") {
                getShowData()
            }
        })
    };
    //批量删除
    const batchDelete = async () => {
        // 获取复选框信息id
        const ids = selectedRows.map((index) => data[index]);
        let delIds: any = []
        await ids.forEach((item: any) => {
            delIds.push(item._id)
        })
        // 批量删除
        axios.post('/specialEducationDel', { id: delIds }).then((res: any) => {
            console.log(delIds);
            if (res.res == "删除成功") {
                message.success(`删除成功`);
                delIds = []
                getShowData()
            }
        })

    }
    //单删
    const [deleteShowOne, setDeleteShowOne1] = useState(false)
    const [delText, setDelText] = useState("")
    const [delId, setDelId] = useState("")
    const ShowDelOne = (val: any) => {
        setDeleteShowOne1(true)
        setDelText(val.title)
        setDelId(val._id)
    }
    const hiddDelete = () => {
        setDeleteShowOne1(false)
    }
    const deleteOne = async () => {
        axios.post('/specialEducationDel', { id: delId }).then((res: any) => {
            if (res.code == 200) {
                message.success(`删除成功`);
                setDeleteShowOne1(false)
                getShowData()
            }
        })
    }
    const listData = () => {
        return data.map((item: any, index: number) => (
            <tr key={index}>
                <td>
                    <input
                        type="checkbox"
                        checked={selectedRows.includes(index)}
                        onChange={(e) => handleRowSelectionChange(index, e.target.checked)}
                    />
                </td>
                <td>{item.title}</td>
                <td>{item.type.name}</td>
                {/* 转类型 */}
                <td>{new Date(item.publishTime).toLocaleDateString("zh-CN", {
                    year: "numeric",
                    month: "2-digit",
                    day: "2-digit",
                })}</td>
                <td>{item.author}</td>
                <td>{item.readingTimes}</td>
                <td>
                    <Switch value={item.isTop} onChange={() => onChangeTop(item._id)} />
                </td>
                <td>
                    <Switch value={item.isRecommend} onChange={() => onChangeRecommend(item._id)} />
                </td>
                <td>
                    <Switch value={item.isCarousel} onChange={() => onChangeCarousel(item._id)} />
                </td>
                <td className='operation'>
                    <span onClick={() => navigate(`/app/addSpecialEducation`, { state: { data: item, state: '编辑' } })}>编辑</span>
                    <span onClick={() => { ShowDelOne(item) }}>删除</span>
                </td>
            </tr>
        ));
    };
    // 分页
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(5);
    const [total, setTotal] = useState(0);
    const handlePageSizeChange = (page: number, pageSize: number) => {
        console.log(page, pageSize);
        setCurrent(page);
        setPageSize(pageSize);

    }
    const onPageSizeChange = (page: number, pageSize: number) => {
        setCurrent(page);
        setPageSize(pageSize);

    }
    useEffect(() => {
        getShowType();
        getShowData();
    }, [pageSize, current]);
    return (
        <div className='maxBox'>
            <div className='content'>
                <div className='content-header'>
                    <Button text='新增图文' setColor='#fff' onClick={() => navigate('/app/addSpecialEducation', { state: { state: '新增' } })} />
                    <Button text='批量删除' setColor='#fff' onClick={() => batchDelete()} className='deleteBut' />
                    <label htmlFor="">标题</label>
                    <InputComponent onChange={setSearchTitleChange} value={SearchTitle} />
                    <Button text='查询' setBackgroundColor='#800000' setColor='#fff' onClick={getShowData} />
                    <Button text='重置' setBackgroundColor='#C0C0C0' setColor='#fff' disabled={resetButtonDisabled} onClick={resetSearch} /> {/* 使用 resetButtonDisabled 状态 */}
                </div>
                <div className='content-body'>
                    <div className='content-body-side'>
                        <div className='content-body-side-title'>
                            <label htmlFor=""><b>类型</b></label>
                            <PlusOutlined style={{ color: '#DC143C' }} onClick={showTypeUpdate} />
                        </div>
                        <div className='content-body-side-main'>
                            <span style={{ color: '#DC143C' }} onClick={() => setSearchTypeChange('')}>全部</span>
                            {
                                type.map((item: any, index: number) => (
                                    <ul key={index}>
                                        <li >
                                            <label htmlFor="" style={{ cursor: 'pointer' }} onClick={() => setSearchTypeChange(item.name)}>{item.name}</label>
                                            <span>
                                                <FormOutlined style={{ color: '#DC143C' }} onClick={() => showTypeEditModal(item)} />
                                                <DeleteOutlined style={{ color: '#DC143C' }} onClick={() => checkTypeDelete(item)} />
                                            </span>
                                        </li>
                                    </ul>
                                ))
                            }
                        </div>
                        {/* 模态框 */}
                        {/* 类型新增 */}
                        <Modal title="新增类型" open={isTypeUpdate} onOk={setTypeUpdateServer} onCancel={hideTypeUpdate}>
                            <InputComponent onChange={setTypeUpdate} value={updateTypeText} width={'100%'} />
                        </Modal>
                        {/* 类型删除 */}
                        <Modal title="删除类型" open={isTypeDelete} onOk={deleteTypeServer} onCancel={hideTypeDelete}>
                            <p>确定删除<big style={{ color: "#DC143C" }}>{deleteTypeName}</big>类型吗？</p>
                        </Modal>
                        {/* 类型修改 */}
                        <Modal title="修改类型" open={TypeEditState} onOk={handleTypeEditOk} onCancel={hideTypeEditModal}>
                            <InputComponent onChange={changeTypeEditInit} value={TypeEditInit} width={'100%'} />
                        </Modal>
                        {/* 数据单删 */}
                        <Modal title="删除" open={deleteShowOne} onOk={deleteOne} onCancel={hiddDelete}>
                            <p>确定删除标题为<big style={{ color: "#DC143C" }}>{delText}</big>的数据吗？</p>
                        </Modal>
                    </div>
                    <div className='content-body-main'>
                        <div className='table-container'>
                            <table>
                                <thead>
                                    <tr>
                                        <th>
                                            <input
                                                type="checkbox"
                                                checked={selectedRows.length === data.length}
                                                onChange={(e) => setSelectedRows(e.target.checked ? data.map((_, i) => i) : [])}
                                            />
                                        </th>
                                        {columns.map(column => <th key={column}>{column}</th>)}
                                    </tr>
                                </thead>
                                <tbody>
                                    {listData()}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                {/* 分页 */}
                <Paging total={total} onChange={onPageSizeChange} onSizeChange={handlePageSizeChange} currentPage={current} pageSize={pageSize} pageSizeOptions={[1, 2, 5, 10, 20]} />
            </div>
        </div>
    );
}
